package com.czxy.enterprise.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czxy.domain.TbCity;
import com.czxy.enterprise.mapper.CityMapper;
import com.czxy.enterprise.service.CityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 城市表 服务实现类
 * </p>
 *
 * @author xuewen
 * @since 2022-01-25
 */
@Service
public class CityServiceImpl extends ServiceImpl<CityMapper, TbCity> implements CityService {

    @Override
    public List<TbCity> findAllCity() {
        List<TbCity> list = this.baseMapper.selectList(new QueryWrapper<TbCity>().orderByAsc("city_id"));
        Map<String,TbCity> catchMap = new HashMap<>();
        List<TbCity> cities = new ArrayList<>();
        for (TbCity tbCity : list) {
            TbCity city = catchMap.get(tbCity.getParentId());
            if (city==null){
                cities.add(tbCity);
            }else {
                if (city.getChildren()==null){
                    city.setChildren(new ArrayList<>());
                }
                city.getChildren().add(tbCity);
            }
            catchMap.put(tbCity.getCityId(),tbCity);
        }
        return cities;
    }

    @Override
    public List<TbCity> findCityById(Integer id) {
        QueryWrapper queryWrapper  = new QueryWrapper();
        queryWrapper.eq("parent_id",id);
        queryWrapper.orderByAsc("city_id");
        List<TbCity> list = this.baseMapper.selectList(queryWrapper);
        return list;
    }
}
